package com.stage.calculator;

import com.stage.model.SleepData;


import javax.servlet.ServletContext;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by fadinglan on 2017/4/18.
 */
public class StageSleep {

    private ServletContext context = null;
    private static boolean isRunning = false;
    ScheduledExecutorService scheduler;
    ExecutorService executor;

    private List<SleepData> sleepDataList = new ArrayList<>();


    public StageSleep(ServletContext context, ScheduledExecutorService scheduler, ExecutorService executor){
        this.context = context;
        this.scheduler = scheduler;
        this.executor = executor;
    }

    public void taskBegin(){
        @SuppressWarnings("null")
        Runnable task = new Runnable() {
            @Override
            public void run() {

                if(!isRunning){
                    isRunning = true;
                    context.log("分期计算开始");
                    Connection yun = null;
                    String URL = "jdbc:mysql://139.224.54.233:3306/familysleep?useUnicode=true&characterEncoding=utf-8&useSSL=false";

                    try{
                        Class.forName("com.mysql.jdbc.Driver");
                        yun = DriverManager.getConnection(URL, "102Xi102", "X123456i");
                        yun.setAutoCommit(false);
                    }catch (ClassNotFoundException e1){
                        e1.printStackTrace();
                    }catch (SQLException e2){
                        e2.printStackTrace();
                    }

                    //查询数据库
                    sleepDataList = query(yun);

                    context.log("query list size is: " + sleepDataList.size());

                    if (sleepDataList != null && !sleepDataList.isEmpty()){
                        CountDownLatch mDoneSingal = new CountDownLatch(sleepDataList.size());

                        for (int i = 0; i < sleepDataList.size(); i++){
                            SleepData data = sleepDataList.get(i);
                            String strHeart = data.getHeartRate();
                            context.log("heart length is :" + strHeart.length());
                            if (strHeart.length() > 1200){
                                executor.submit(new EstimateStage(mDoneSingal, i, context, data, yun));
                            }else {
                                mDoneSingal.countDown();
                            }
                        }

                        try {
                            mDoneSingal.await();  //等待所有线程结束
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }else {
                        context.log("暂无数据");
                    }

                    if (yun != null){
                        try {
                            yun.close();
                        } catch (SQLException e){
                            e.printStackTrace();
                        }
                    }
                    isRunning = false;
                    context.log("分期任务结束");

                }else {
                    context.log("上次执行任务还未结束");
                }


            }
        };
        scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.MINUTES);


    }

    public static List<SleepData> query(Connection con){

        String sql = "select * from sleep_data";
        PreparedStatement ps =null;
        ResultSet rs = null;
        List<SleepData> sleepDataList = new ArrayList<>();
        try{
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            con.commit();
            while (rs.next()){
                SleepData sleepData = new SleepData();
                sleepData.setDeviceId(rs.getLong("deviceId"));
                sleepData.setStartTime(rs.getString("startTime"));
                sleepData.setHeartRate(rs.getString("heartRate"));
//                sleepData.setSleepMove(rs.getString("sleepMove"));
                sleepDataList.add(sleepData);
            }
        }catch (SQLException e){
            //查询异常进行事务回滚
            try{
                System.out.println("查询数据库异常");
                con.rollback();
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            //关闭存储查询结果的resultSet对象
            if (rs != null){
                try{
                    rs.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }

            //关闭负责执行SQL命令的prepareStatement对象

            if(ps != null){
                try {
                    ps.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }


        }
        return sleepDataList;

    }

    public void taskEnd(){
        scheduler.shutdown();
    }
}
